package nico.styTool.builder

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.ApplicationInfo
import android.os.SystemClock.sleep
import cn.vove7.bottomdialog.builder.BindView
import cn.vove7.bottomdialog.builder.ListAdapterBuilder
import cn.vove7.bottomdialog.builder.OnItemClick
import cn.vove7.bottomdialog.util.ObservableList
import com.blankj.utilcode.util.AppUtils.getAppIcon
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.item_app_list.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import nico.styTool.R
import kotlin.concurrent.thread

class AppListBuilder(
    context: Context,
    autoDismiss: Boolean = true,
    private val appList: ObservableList<AppInfo> = ObservableList(),
    onItemClick: OnItemClick<AppInfo>
) : ListAdapterBuilder<AppInfo>(appList, autoDismiss, onItemClick) {

    init {
        loading = true
        thread {
            sleep(1500)
            loadAppList(context)
        }
    }

    override val itemView: (type: Int) -> Int = { R.layout.item_app_list }

    override val bindView: BindView<AppInfo> = { view, item ->
        view.textView_name.text = item.name
        view.textView_pak.text = item.pkg
        GlobalScope.launch(Dispatchers.Main) {
            delay(1000)
            Glide.with(context).load(getAppIcon(item.pkg)).into(view.imageView_icon)
        }
    }

    @SuppressLint("QueryPermissionsNeeded")
    private fun loadAppList(context: Context) {
        val pm = context.packageManager
        appList.addAll(ObservableList.build {
            pm.getInstalledPackages(0)
                .filter { ApplicationInfo.FLAG_SYSTEM and it.applicationInfo.flags == 0 }
                .forEach {
                    add(AppInfo(it.packageName, it.applicationInfo.loadLabel(pm)))
                }
        })
        loading = false
    }
}


data class AppInfo(
    val pkg: String,
    val name: CharSequence
)